package com.yunlong.interceptor;

import com.yunlong.common.TokenInfo;
import com.yunlong.common.UserInfoDto;
import com.yunlong.common.constant.SysConstant;
import com.yunlong.constant.OrderConstant;
import com.yunlong.token.TokenService;
import com.yunlong.util.JsonUtil;
import com.yunlong.util.ThreadLocalMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import com.yunlong.wrapper.ResultWrapper;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lgr
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    private boolean ifManage = false;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        System.out.println(request);
        if (request.getMethod().equalsIgnoreCase("options")) {
            return true;
        }
        String accessToken = null;
//        先查找请求头
//        ORDER_ACCESS_TOKEN
        accessToken = request.getHeader(OrderConstant.HTTP_HEADER_ORDER_ACCESS_TOKEN);
//        当请求头不存在时，再去找请求参数
//        accessToken
        if (null == accessToken){
            System.out.println("sssssss");
            accessToken = request.getParameter(OrderConstant.RQE_PARAM_ORDER_ACCESS_TOKEN);
        }

        ResultWrapper resultWrapper = null;
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        System.out.println("ssss"+accessToken);
        /**
         * 未传递Token
         */
        if (null == accessToken|"".equals(accessToken)){
//            THREAD_LOCAL_KEY_LOGIN_USER
            ThreadLocalMap.remove(SysConstant.THREAD_LOCAL_KEY_LOGIN_USER);
            resultWrapper = ResultWrapper.failure("未认证");
            //SC_UNAUTHORIZED  =  401
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            try {
                //输出未认证的报错信息
                response.getWriter().println(JsonUtil.toJson(resultWrapper));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }
        //走到这里，说明存在token，但正确性还没有得到检验
        TokenInfo tokenInfo = tokenService.getTokenInfo(accessToken);
        //为什么判断为null，为null说明是第一次登录操作，redis还没有保存token
        if (null == tokenInfo){
            //检验是否为管理员
            tokenInfo = tokenService.getManagerInfo(accessToken);
            if (tokenInfo == null) {
                ThreadLocalMap.remove(SysConstant.THREAD_LOCAL_KEY_LOGIN_USER);
                resultWrapper = ResultWrapper.failure("错误的Token");
                //SC_BAD_REQUEST  400
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                try {
                    response.getWriter().println(JsonUtil.toJson(resultWrapper));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            } else {
                //说明是管理员
                ifManage = true;
            }
        }

        /**
         * 将userInfo设置到ThreadLocal,只要调用接口，就会创建userInfoDto
         */
        UserInfoDto userInfoDto = new UserInfoDto();
        userInfoDto.setUserId(tokenInfo.getUserId());
        userInfoDto.setIfManager(ifManage);
//        THREAD_LOCAL_KEY_LOGIN_USER  -  THREAD_LOCAL_KEY_LOGIN_USER
        ThreadLocalMap.put(SysConstant.THREAD_LOCAL_KEY_LOGIN_USER, userInfoDto);
        System.out.println("用户ID为："+userInfoDto.getUserId());
        return true;
    }
}
